from django.shortcuts import render

# Create your views here.
from django.views import View
from utils.views import LoginRequiredJSONMixin
from apps.users.models import Address
from django_redis import get_redis_connection
from apps.goods.models import SKU
from django.http import JsonResponse

class OrderSettlementView(LoginRequiredJSONMixin,View):
    def get(self,request):
        #获取用户
        user=request.user

        #查询用户地址信息
        addresses=Address.objects.filter(is_deleted=False)
        addresses_list=[]
        for address in addresses:
            addresses_list.append({
                'id': address.id,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'receiver': address.receiver,
                'mobile': address.mobile
            }
            )

        #购物车中选中商品信息
        #链接redis
        redis_cli=get_redis_connection('carts')
        pipeline=redis_cli.pipeline()
        pipeline.hgetall('carts_%s' % user.id)
        pipeline.smembers('selected_%s' % user.id)
        result = pipeline.execute()

        sku_id_counts = result[0]
        selected_ids=result[1]



        #  selected_carts = {sku_id:count}
        selected_carts = {}
        for sku_id in selected_ids:
            selected_carts[int(sku_id)] = int(sku_id_counts[sku_id])

        # {sku_id:count,sku_id:count}
        #     3.5 根据商品的id 查询商品的具体信息 [SKU,SKU,SKu...]
        sku_list = []
        for sku_id, count in selected_carts.items():
            sku = SKU.objects.get(pk=sku_id)
            #     3.6 需要将对象数据转换为字典数据
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'count': count,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        # 运费
        from decimal import Decimal
        freight = Decimal('10')

        context = {
            'skus': sku_list,
            'addresses': addresses_list,
            'freight': freight
        }

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'context': context})




    ###################点击提交订单,生成订单##########################################
import json
from apps.orders.models import OrderInfo,OrderGoods
from django.db import transaction

class OrderCommitView(LoginRequiredJSONMixin,View):

    def post(self,request):
        user=request.user
        #1 接受请求
        data=json.loads(request.body.decode())
        address_id=data.get('address_id')
        pay_method=data.get('pay_method')

    #2 验证数据
        if not all ([address_id,pay_method]):
            return  JsonResponse ({'code':400,'errmsg':'参数不全'})

        try:
            address=Address.objects.get (id=address_id)
        except Address.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'参数不正确'})

        if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'],OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:
            return JsonResponse({'code': 400, 'errmsg': '参数不正确'})


        from django.utils import timezone

        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S%f') + '%09d' % user.id

        if pay_method == OrderInfo.PAY_METHODS_ENUM['CASH']:
            status=OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        else:
            status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']


        total_count=0
        from decimal import Decimal
        total_amount=Decimal('0')

        freight=Decimal('10.00')

        with transaction.atomic(): #####开始实物
            point= transaction.savepoint() #########创建保存点
            # 数据入库
            orderinfo = OrderInfo.objects.create(
                order_id=order_id,
                user=user,
                address=address,
                total_count=total_count,
                total_amount=total_amount,
                freight = freight,
                pay_method = pay_method,
                status = status,)
            redis_cli=get_redis_connection('carts')
            sku_id_counts=redis_cli.hgetall('carts_%s'%user.id)
            # 获取set
            selected_ids=redis_cli.smembers('selected_%s'%user.id)

            carts={}


            for sku_id in selected_ids:
                carts[int(sku_id)]=int (sku_id_counts[sku_id])

            for sku_id,count in  carts.items():
                while True:
                    sku=SKU.objects.get(id=sku_id)

                    if sku.stock<count:
                        #### 回滚到保存点
                        transaction.savepoint_rollback(point)

                        return  JsonResponse({'code':400,'errmsg':'库存不足'})


                    from time import sleep
                    sleep(8)
                    old_stock=sku.stock
                    new_stock=sku.stock-count
                    new_stock=sku.sales+count

                    result=SKU.objects.filter(id=sku_id,stock=old_stock).update(stock=new_stock,sales=new_sales)


                    if result==0:

                        continue

                    orderinfo.total_count += count
                    orderinfo.total_amount += (count * sku.price)
               ########保存订单商品信息

                    OrderGoods.objects.create(
                        order=orderinfo,
                        sku=sku,
                        count=count,
                        price= sku.price
                    )

                    break

                orderinfo.save()######更新订单的总金额和总数量

                #####提交点
                transaction.savepoint_commit(point)


        return JsonResponse({'code':0,'errmsg':'ok','order_id':order_id})




